package com.pandi.springboot_jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Component;

import java.awt.image.Kernel;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pandi
 * @create 2020-12-30 22:05
 */

public class JWTUtils {

    private static final String SING = "token@pandi";

    /**
     * 生成token  head.payload.sing
     */
    public static String getToken(Map<String,String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);  //7天之后过期
        //创建JWT Builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v) ->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime()) //指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));//签名

        return token;
    }

    /**
     * 验证token
     */
     public static DecodedJWT verify(String token){

         DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);

         return verify;

     }


}
